﻿using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IRepository;
using Infrastructures;

namespace ConcreteService
{
    public class LogUtil
    {
        internal LogUtil() { }

        public static void Create(EventLog log)
        {
            ILogRepository repo = ServiceFactory.CreateInstance<ILogRepository>();
            log.ActionTime = DateTime.Now;
            log.InstanceID = SystemConfig.Get("InstanceID");
            repo.Create(log);
        }

        public static void Create(string eventID, EventType type, string objName, string message)
        {
            ILogRepository repo = ServiceFactory.CreateInstance<ILogRepository>();
            EventLog log = new EventLog();
            log.ActionType = type;
            log.Operator = SystemConfig.Get("SysEventID");
            log.Remark = message;
            log.EventID = eventID;
            log.ActionObject = objName;
            log.ActionTime = DateTime.Now;
            log.InstanceID = SystemConfig.Get("InstanceID");
            repo.Create(log);
        }

        public static void Create(string oper, string message)
        {
            ILogRepository repo = ServiceFactory.CreateInstance<ILogRepository>();
            EventLog log = new EventLog();
            log.ActionType = EventType.SysError;
            log.Operator = oper;
            log.Remark = message;
            log.EventID = SystemConfig.Get("SysEventID");
            log.ActionObject = EventType.SysError.ToString();
            log.ActionTime = DateTime.Now;
            log.InstanceID = SystemConfig.Get("InstanceID");
            repo.Create(log);
        }

        public static void CreateForException(Exception ex, string oper, string url = "")
        {
            StringBuilder sb = new StringBuilder(2000);
            sb.Append("Message: " + ex.Message);

            if (!string.IsNullOrWhiteSpace(url))
                sb.Append("Url: " + url);

            if (ex.InnerException != null)
            {
                sb.Append(" InnerException.Message: " + ex.InnerException.Message);
                sb.Append(" StackTrace: " + ex.InnerException.StackTrace);
            }

            if (sb.Length > 4000)
                sb.Remove(3999, sb.Length);

            Create(oper, sb.ToString());
        }

        public static List<EventLog> List(string eventID)
        {
            ILogRepository repo = ServiceFactory.CreateInstance<ILogRepository>();
            return repo.List(eventID);
        }

        public static List<EventLog> List(EventType type, string eventObj)
        {
            ILogRepository repo = ServiceFactory.CreateInstance<ILogRepository>();
            return repo.List(type, eventObj);
        }
    }
}
